#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("Websocket - 服务器");
    // 实例化Websocket服务器对象
    m_server = new QWebSocketServer("MyServer", QWebSocketServer::NonSecureMode, this);

    connect(ui->listenBtn, &QPushButton::clicked, this, [=](){
        quint16 port = ui->port->text().toInt();
        if(m_server->listen(QHostAddress::Any, port))
        {
            connect(m_server, &QWebSocketServer::newConnection, this, &MainWindow::onNewConnection);
            ui->listenBtn->setDisabled(true);
        }
    });
    connect(ui->sendBtn, &QPushButton::clicked, this, [=](){
        QString msg = ui->sendMsgInfo->toPlainText();
        if(m_socket)
        {
            m_socket->sendTextMessage(msg);
        }
        ui->sendMsgInfo->clear();
        ui->recvMsgInfo->append("服务器: " + msg);
    });

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onNewConnection()
{
    m_socket = m_server->nextPendingConnection();
    connect(m_socket, &QWebSocket::textMessageReceived, this, [=](const QString &msg){
        ui->recvMsgInfo->append("客户端: " + msg);
    });
    connect(m_socket, &QWebSocket::disconnected, m_socket, &QWebSocket::deleteLater);

}
